package cn.kevinproject.dingtalk_robot.datacenter;

import cn.kevinproject.dingtalk_robot.client.ProducerFactory;
import cn.kevinproject.dingtalk_robot.msg.FeedCardMessage;
import cn.kevinproject.dingtalk_robot.robot.Robot;
import cn.kevinproject.dingtalk_robot.robot.RobotManger;
import com.google.common.base.Throwables;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author kevin lau
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class DataSender {

    private final DataGrabRegistrar dataGrabRegistrar;

    private final ProducerFactory producerFactory;

    private final RobotManger robotManger;

    public void send(String key, String robot) {
        Robot r = robotManger.getRobot(robot);
        if (r == null) {
            return;
        }
        final DataGrab dataGrab = dataGrabRegistrar.getDataGrab(key);
        if (dataGrab == null) {
            return;
        }
        List<FeedCardMessage.Link> value;
        try {
            value = dataGrab.grabData();
        } catch (Exception e) {
           log.error("grab data error cause:{}", Throwables.getStackTraceAsString(e));
           return;
        }
        val feed = new FeedCardMessage();
        feed.setLinks(value);
        producerFactory.buildProducer(robot).sendMsg(feed);
    }
}
